<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true" id="searchFormId" @submit.prevent>
        <el-form-item label="商品名称" prop="name">
          <el-input placeholder="请输入商品名称" v-model="searchParams.name" clearable style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="是否参与分销" prop="name">
          <el-select placeholder="请是否参与分销" v-model="searchParams.is_agent" clearable style="width: 240px">
            <el-option label="参与分销" value="1" />
            <el-option label="未参与分销" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" :disabled="ids.length <= 0" plain @click="handleJoinMultiple()">
            批量设置分销
          </el-button>
          <el-button type="danger" :disabled="ids.length <= 0" plain @click="handleDelMultiple()">
            批量取消分销
          </el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refresh-table="handleListPage"></KoiToolbar>
      </el-row>

      <br />
      <el-table
        v-loading="loading"
        v-adaptive
        border
        :data="tableList"
        empty-text="暂时没有数据哟"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" :selectable="canBeSelect"> </el-table-column>
        <el-table-column label="序号" prop="id" width="80px" align="center" type="index"> </el-table-column>
        <el-table-column label="商品名称" prop="name" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="商品图片" prop="avatar" width="100px" align="center">
          <template #default="scope">
            <div class="flex justify-center">
              <el-image
                class="w-72px h-72px"
                :preview-teleported="true"
                :preview-src-list="scope.row.slider_image"
                :src="
                  scope.row.slider_image[0] != null && scope.row.slider_image[0] !== ''
                    ? scope.row.slider_image[0]
                    : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
                "
              >
                <template #error>
                  <el-icon class="c-[--el-color-primary]" :size="36">
                    <CircleCloseFilled />
                  </el-icon>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="price_text" align="center" :show-overflow-tooltip="true"></el-table-column>

        <el-table-column label="商品分类" prop="unit" align="center" width="200px" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ [scope.row.cate1?.name, scope.row.cate2?.name, scope.row.cate3?.name].filter(r => r).join("/") }}
          </template>
        </el-table-column>
        <el-table-column label="商品品牌" prop="brand.name" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="是否参与" prop="brand.name" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.agent ? "参与" : "未参与" }}
          </template>
        </el-table-column>
        <el-table-column label="分销规则" prop="brand.name" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ !scope.row.agent ? "" : scope.row.agent?.type == 1 ? scope.row.agent?.rule.name : "独立配置" }}
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          align="left"
          width="350"
          fixed="right"
          v-auth="['system:role:update', 'system:role:delete']"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              plain
              v-if="!row.agent"
              @click="handleJoin(row)"
              v-auth="['system:role:update']"
            >
              参与分销
            </el-button>
            <el-button
              type="danger"
              size="small"
              plain
              v-if="row.agent"
              @click="handleUpdate(row)"
              v-auth="['system:role:update']"
            >
              分销设置
            </el-button>
            <el-button type="warning" size="small" plain v-if="row.agent" @click="handleDel(row)" v-auth="['system:role:update']">
              取消分销
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <br />
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDrawer
        ref="koiDrawerRef"
        :title="title"
        @koi-confirm="handleConfirm"
        @koi-cancel="handleCancel"
        :loading="confirmLoading"
        :size="1000"
      >
        <template #content>
          <el-descriptions title="基础信息" border style="margin-bottom: 10px">
            <el-descriptions-item label="商品名称">{{ info?.name }}</el-descriptions-item>
            <el-descriptions-item label="商品分类"
              >{{ info?.cate1?.name }}/{{ info?.cate2?.name }}/{{ info?.cate3?.name }}</el-descriptions-item
            >
            <el-descriptions-item label="商品品牌">{{ info?.brand?.name }}</el-descriptions-item>
            <el-descriptions-item label="主图">
              <el-image
                class="rounded-full w-72px h-72px"
                :preview-teleported="true"
                :preview-src-list="info?.slider_image"
                :src="
                  info?.main_image != null && info?.main_image !== ''
                    ? info?.main_image
                    : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
                "
              >
                <template #error>
                  <el-icon class="c-[--el-color-primary]" :size="36">
                    <CircleCloseFilled />
                  </el-icon>
                </template>
              </el-image>
            </el-descriptions-item>
          </el-descriptions>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
            <el-form-item label="分销类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="1">规则配置</el-radio>
                <el-radio :label="2">独立设置</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="规则模板" prop="one_rate" v-if="form.type == 1">
              <el-select v-model="form.rule_id" placeholder="请选择规格模板" size="large" @change="changeRule">
                <el-option v-for="(item, index) in ruleList" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="一级比例" prop="one_rate">
              <el-input v-model="form.one_rate" :disabled="form.type == 1" placeholder="请输入一级比例" clearable>
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="二级比例" prop="two_rate">
              <el-input v-model="form.two_rate" :disabled="form.type == 1" placeholder="请输入二级比例" clearable>
                <template #append>%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="三级比例" prop="three_rate">
              <el-input v-model="form.three_rate" :disabled="form.type == 1" placeholder="请输入三级比例" clearable>
                <template #append>%</template>
              </el-input>
            </el-form-item>
          </el-form>
        </template>
      </KoiDrawer>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="agentRulePage">
import { delAgentGoods, joinAgentGoods, listPage, read, updateAgentGoods } from "@/plugin/agent/api/goods/index.ts";
import { koiMsgBox, koiMsgError, koiMsgWarning, koiNoticeError, koiNoticeSuccess } from "@/utils/koi.ts";
import { onMounted, reactive, ref } from "vue";
import { getAllRules } from "../../api/rule";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([]);
// 查询参数
const searchParams = ref({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  name: "",
  is_agent: "",
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    name: "",
    is_agent: "",
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

// 时间
/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};
const ruleList = ref<any>();
onMounted(() => {
  // 获取数据表格数据
  handleListPage();
  initRules();
});

const initRules = async () => {
  const { data } = await getAllRules();
  ruleList.value = data;
};
const changeRule = () => {
  const one = ruleList.value.find((r: any) => r.id == form.value.rule_id);
  if (one) {
    form.value.one_rate = one.one_rate;
    form.value.two_rate = one.two_rate;
    form.value.three_rate = one.three_rate;
  }
};

const info = ref<any>();
/** 回显数据 */
const handleEcho = async (row: any) => {
  try {
    const { data }: any = await read({
      id: row.agent?.id,
      goods_id: row.id
    });
    info.value = data.goodsInfo;
    form.value = data?.info;
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 重置表单
  resetForm();
  // 标题
  title.value = "修改";
  const id = row.id;
  if (id == null || id == "") {
    koiMsgError("请选中需要修改的数据");
  }
  handleEcho(row);
  koiDrawerRef.value.koiOpen();
};

/** 添加 AND 修改抽屉 */
const koiDrawerRef = ref();
// 标题
const title = ref("");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  name: "",
  status: 1
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    name: "",
    status: 1
  };
};

/** 表单规则 */
const rules = reactive({});

// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      try {
        updateAgentGoods(form.value);
        resetForm();
        handleListPage();
        koiDrawerRef.value.koiQuickClose();
      } catch (error) {
        console.log(error);
        confirmLoading.value = false;
        koiNoticeError("操作失败，请刷新重试");
      } finally {
        confirmLoading.value = false;
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};
const handleDel = (row: any) => {
  koiMsgBox("确认取消分销吗？")
    .then(async () => {
      resetForm();
      if (!row.id) {
        koiMsgWarning("请选择需要取消的数据");
        return;
      }
      await delAgentGoods({
        goods_ids: [row.id]
      });
      koiNoticeSuccess("取消成功");
    })
    .catch(() => {})
    .finally(() => {
      handleTableData();
    });
};
const handleJoin = (row: any) => {
  koiMsgBox("确认参与分销吗？")
    .then(async () => {
      resetForm();
      if (!row.id) {
        koiMsgWarning("请选择需要参与的数据");
        return;
      }
      await joinAgentGoods({
        goods_ids: [row.id]
      });
      koiNoticeSuccess("参与成功");
    })
    .catch(() => {})
    .finally(() => {
      handleTableData();
    });
};

const handleJoinMultiple = () => {
  koiMsgBox("确认批量参与分销吗？")
    .then(async () => {
      resetForm();
      if (ids.value.length <= 0) {
        koiMsgWarning("请选择需要参与的数据");
        return;
      }
      await joinAgentGoods({
        goods_ids: ids.value
      });
      koiNoticeSuccess("参与成功");
    })
    .catch(() => {})
    .finally(() => {
      handleTableData();
    });
};
const handleDelMultiple = () => {
  koiMsgBox("确认批量取消分销吗？")
    .then(async () => {
      resetForm();
      if (ids.value.length <= 0) {
        koiMsgWarning("请选择需要取消的数据");
        return;
      }
      await delAgentGoods({
        goods_ids: ids.value
      });
      koiNoticeSuccess("参与成功");
    })
    .catch(() => {})
    .finally(() => {
      handleTableData();
    });
};

/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(searchParams.value);
    console.log("表格数据->>>>>>>>>>>>>>>", res.data);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};
const ids = ref([]); // 选中数组
/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
};

const canBeSelect = (_row: any) => {
  return true;
  // return !row.agent;
};
</script>

<style lang="scss" scoped></style>
